// https://leetcode.cn/problems/map-of-highest-peak/description/

// 算法思路总结：
// 1. 多源BFS从所有水域单元格开始同步扩散
// 2. 水域初始高度为0，陆地高度逐层递增
// 3. 使用队列按层处理保证相邻单元格高度差为1
// 4. 通过访问标记避免重复计算
// 5. 时间复杂度：O(m×n)，空间复杂度：O(m×n)

#include <iostream>
using namespace std;

#include <vector>
#include <algorithm>
#include <cstring>
#include <queue>

class Solution 
{
public:
    int m, n;
    int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
    bool vis[1010][1010];
    typedef pair<int, int> PII;

    vector<vector<int>> highestPeak(vector<vector<int>>& isWater) 
    {
        m = isWater.size(), n = isWater[0].size();
        memset(vis, 0, sizeof(vis));

        queue<PII> q;
        for (int i = 0 ; i < m ; i++)
        {
            for (int j = 0 ; j < n ; j++)
            {
                if (isWater[i][j] == 1)
                {
                    isWater[i][j] = 0;
                    vis[i][j] = true;
                    q.push({i, j});
                }
            }
        }

        int step = 0;
        while (!q.empty())
        {
            int sz = q.size();
            step++;
            while (sz--)
            {
                auto [a, b] = q.front();
                q.pop();

                for (int i = 0 ; i < 4 ; i++)
                {
                    int x = a + dx[i], y = b + dy[i];
                    if (x >= 0 && y >= 0 && x < m && y < n && isWater[x][y] == 0 && vis[x][y] == false)
                    {
                        isWater[x][y] = step;
                        vis[x][y] = true;
                        q.push({x, y});
                    }
                }
            }
        }

        return isWater;
    }
};

int main()
{
    vector<vector<int>> isWater1 = {{0,1},{0,0}};
    vector<vector<int>> isWater2 = {{0,0,1},{1,0,0},{0,0,0}};
    Solution sol;

    auto vv1 = sol.highestPeak(isWater1);
    auto vv2 = sol.highestPeak(isWater2);

    for (const auto& v : vv1)
    {
        for (const int& num : v)
        {
            cout << num << " ";
        }
        cout << endl;
    }
    cout << endl;

    for (const auto& v : vv2)
    {
        for (const int& num : v)
        {
            cout << num << " ";
        }
        cout << endl;
    }
    cout << endl; 

    return 0;
}